package com.victor9ac.tfm.mashup.connector.adapter.jersey;

import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.victor9ac.tfm.mashup.connector.exception.MashupConnectionException;

public class JerseyConnector  {



	private ClientConfig config;

	private int connTimeout;
	private int soTimeout;
	private int readTimeout;
	private String host;
	private String context;

	
	public JerseyConnector() {
		connTimeout=2000;
		soTimeout=2000;
		readTimeout=2000;
		
		config = new DefaultClientConfig();
	}

	
	public Object execute(String resource, Class mapeableClass) throws MashupConnectionException{

		Object result = null;
		
		Client client = Client.create(config);
		
		client.setConnectTimeout(connTimeout);
		client.setReadTimeout(soTimeout);
		client.setReadTimeout(readTimeout);
		
		WebResource webResource = client.resource(UriBuilder.fromUri(host+"/"+context+"/"+resource).build());
		// getting XML data
		
		
		Builder myRestWebService = webResource.accept("application/json").type("application/json");
		
		try {
			myRestWebService.get(mapeableClass);
		} catch (UniformInterfaceException e) {
			throw new MashupConnectionException("No 200 code,",e);
		}

		
		
		return result;

	}
	
	
	public void setConfig(ClientConfig config) {
		this.config = config;
	}


	public void setConnTimeout(int connTimeout) {
		this.connTimeout = connTimeout;
	}


	public void setSoTimeout(int soTimeout) {
		this.soTimeout = soTimeout;
	}


	public void setReadTimeout(int readTimeout) {
		this.readTimeout = readTimeout;
	}


	public void setHost(String host) {
		this.host = host;
	}


	public void setContext(String context) {
		this.context = context;
	}


}
